package club.pchome.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import club.pchome.common.constant.SystemConstant;
import club.pchome.dto.Result;
import club.pchome.dto.UserInfoDto;
import club.pchome.model.AutoSign;
import club.pchome.service.AutoSignService;
import club.pchome.service.UserInfoService;
import club.pchome.util.DateUtil;
import club.pchome.util.JsoupSignAdm;
@Api(tags = { "用户资料详情接口" })
@RestController
public class UserInfoController extends BaseController{

	@Autowired
	AutoSignService autoSignService;

	@Autowired
	UserInfoService userInfoService;

	@Autowired
	JsoupSignAdm signAdm;

	/**
	 *  按归属人更新用户数据
	 * @param request
	 * @param userName == null ? update_all : update_holder
	 * @return
	 */
	@PostMapping("/updataUser")
	public Result<String> updataUser(String userName, String NC){
		long startTime=System.currentTimeMillis(); //执行方法
		List<AutoSign> list = null;
		if(NC != null){
			list = autoSignService.updateHolderNC();
		}else{
			list = autoSignService.getUserHolder(userName);
		}

		int count = list.size();
		if(list.size() > 0) {

			for (AutoSign autoSign : list) {
				//获取cookie
				String JSESSIONID  = ADMLOGIN(autoSign.getPhone() , autoSign.getPwd());

				if(!JSESSIONID.equals("10021")) {
					UserInfoDto user = new UserInfoDto();

					/*************************** 用户资料数据 start*************************/
					//获取用户资料数据
					String ACCOUNT_DATA_RESULT = signAdm.JsoupToDataByCookieAndBody(SystemConstant.ACCOUNT_DATA, "{}", JSESSIONID);
					JSONObject account_data = JSONObject.parseObject(ACCOUNT_DATA_RESULT);

					int status_code = account_data.getInteger("code");
					if(status_code == 200) {
						JSONArray dataList = account_data.getJSONArray("data");
						for (Object obj : dataList) {
							JSONObject __obj   = (JSONObject) obj;
							Integer  coinId    = __obj.getInteger("coinId");
							BigDecimal totalAmount = __obj.getBigDecimal("totalAmount");

							user.setAutosignid(autoSign.getId());
							if(coinId == 1001) { //USDT
								user.setUSTD( totalAmount );
							}else if(coinId == 1002) { // 可售余额
								user.setKSYE( totalAmount );
							}else if(coinId == 1003) { // 可售额度
								user.setKSED( totalAmount );
							}else if(coinId == 1004) { // 矿池钱包
								user.setKCQB(totalAmount );
							}else if(coinId == 1005) { // 矿池资产
								user.setKCZC( totalAmount );
							}else if(coinId == 1006) { // 信用积分
								user.setXYJF( totalAmount );
							}else if(coinId == 1007) { // ADM
								user.setADM( totalAmount );
							}else if(coinId == 1008) { // UT
								user.setUT( totalAmount );
							}else if(coinId == 1009) { // USDT冷钱包
								user.setUSTD2( totalAmount );
							}
						}
					}
					/*************************** 用户资料数据 end*************************/

					/*************************** 农场部分 start*************************/
					//查询农场动物
					String USER_ANIMAL_RESULT = signAdm.JsoupToDataByCookieAndBody(SystemConstant.userAnimalList, "{}" ,JSESSIONID);
					JSONObject userAnimalJson = JSONObject.parseObject(USER_ANIMAL_RESULT);

					int code = userAnimalJson.getInteger("code");

					//有动物的
					if(code == 200) {
						String data = userAnimalJson.getString("data");
						JSONObject dataJson = JSONObject.parseObject(data);
						JSONArray jsonArray = dataJson.getJSONArray("list");

						//由于目前只有1个种类
						JSONObject result = JSONObject.parseObject(jsonArray.get(0).toString());
						//系统鸡的编号 1001 
						int animalId = result.getInteger("animalId");
						//用户的动物编号
						int userAnimalId = result.getInteger("userAnimalId");
						
						long feedTime = result.getLong("feedTime");
						long nextFeedTime = feedTime + 1000 * 60 * 60 * 12;

						user.setIsOpenNC(1);
						user.setUserAnimalId(userAnimalId);
						user.setFeedTime(new Date(feedTime));
						user.setNextFeedTime(new Date(nextFeedTime));
					}
					/*************************** 农场部分 end *****************************/


					/****************************** 用户购买信息 start **********************/
					//获取用户资料数据
					String levelInfoResult = signAdm.JsoupToDataByCookieAndBody(SystemConstant.getNextLevelInfo, "{}", JSESSIONID);
					JSONObject levelInfo = JSONObject.parseObject(levelInfoResult);

					//System.out.println(autoSign.getPhone() + "_"+levelInfoResult);
					int levelInfo_code = levelInfo.getInteger("code");
					if(levelInfo_code == 200) {
						user.setAutosignid(autoSign.getId());
						String detail_data = levelInfo.getString("data");
						JSONObject json_detail = JSONObject.parseObject(detail_data);
						int hangUpCount = json_detail.getInteger("hangUpCount");
						int nextHangUpCount  = json_detail.getInteger("nextHangUpCount");

						user.setHangUpCount(hangUpCount);
						user.setNextHangUpCount(nextHangUpCount);
					}
					/****************************** 用户购买信息 end **********************/

					//判断是否存在
					long isTrue = userInfoService.getCapitalListById(user.getAutosignid());
					if(isTrue > 0) {//存在就更新
						long COUNT = userInfoService.updateCapitalList(user);
						if(COUNT > 0) {
							logger.info("修改账户数据成功@1!  phone = " + autoSign.getPhone());
						}else {
							logger.error("修改账户数据失败@1!  phone = " + autoSign.getPhone());
						}
					}else {// 不存在就写入
						long COUNT = userInfoService.setCapitalList( user );
						if(COUNT > 0) {
							logger.info("写入账户数据失败@1!  phone = " + autoSign.getPhone());
						}else {
							logger.error( "写入账户数据失败@1!  phone = " + autoSign.getPhone());
						}
					}
					
					count--;

				}else {
					//资料错误, 请更新资料
					autoSign.setIsture(1);
					autoSign.setIsscan(1);
					autoSignService.updateAccountInfo(autoSign);
					logger.error("资料错误, 请更新资料 !!!  phone = " + autoSign.getPhone());
				}

			}

		}
		long endTime=System.currentTimeMillis();
		float excTime=(float)(endTime-startTime)/1000;
		return Result.initSuccessResult("更新用户数据成功 , 共 "+list.size() + " 条, 耗时 : " + excTime);
	}

	/**
	 * 获取账号资料等级数据
	 * @param userName
	 * @return
	 */
	@PostMapping("/getNextLevelInfo")
	public Result<String> getNextLevelInfo(String userName){
		long startTime=System.currentTimeMillis(); //执行方法 
		List<AutoSign> list = autoSignService.getUserHolder(userName);
		if(list.size() > 0) {

			for (AutoSign autoSign : list) {
				//获取cookie
				String userInfo = "{\"loginName\":\"" + autoSign.getPhone() +"\",\"pwd\":\""+autoSign.getPwd()+"\"}";
				String JSESSIONID = signAdm.AdmLogin(userInfo);

				if(JSESSIONID != null) {

					//获取用户资料数据
					String levelInfo = signAdm.JsoupToDataByCookie(SystemConstant.getNextLevelInfo, JSESSIONID);
					JSONObject account_data = JSONObject.parseObject(levelInfo);

					UserInfoDto user = new UserInfoDto();

					String status_code = account_data.getString("code");
					if(status_code.equals("200")) {
						user.setAutosignid(autoSign.getId());
						String detail_data = account_data.getString("data");
						JSONObject json_detail = JSONObject.parseObject(detail_data);
						int hangUpCount = json_detail.getInteger("hangUpCount");
						int nextHangUpCount  = json_detail.getInteger("nextHangUpCount");

						user.setHangUpCount(hangUpCount);
						user.setNextHangUpCount(nextHangUpCount);
						//判断是否存在
						long isTrue = userInfoService.getCapitalListById(user.getAutosignid());
						if(isTrue > 0) {//存在就更新
							long COUNT = userInfoService.updateCapitalList(user);
							if(COUNT > 0) {
								//									System.out.println( "修改账户数据成功!" );
							}else {
								Result.initFailureResult( 50001 , "修改账户数据失败! autoSignid = " + user.getAutosignid() );
							}
						}else {// 不存在就写入
							long COUNT = userInfoService.setCapitalList( user );
							if(COUNT > 0) {
								//									System.out.println( "写入账户数据成功!" );
							}else {
								Result.initFailureResult( 50002 , "写入账户数据失败! autoSignid = " + user.getAutosignid() );
							}
						}
					}

				}else {
					Result.initFailureResult( 50003 , "编号 : "+autoSign.getId()+" , loginName : " + autoSign.getPhone() +" , 更新时间失败!!! ");
				}

			}

		}
		long endTime=System.currentTimeMillis();
		float excTime=(float)(endTime-startTime)/1000;
		return Result.initSuccessResult("更新用户数据成功 , 共 "+list.size() + " 条, 耗时 : " + excTime);
	}

	/**
	 *  按归属人兑换钱包
	 * @param userName
	 * 
	 * @return {"amount":"10","coinId":"1004","securityCode":"poiuytrew"}
	 */
	public Result<String> exchangeCapital(String userName){

		List<AutoSign> list = autoSignService.getUserHolder(userName);
		if(list.size() > 0) {

			for (AutoSign autoSign : list) {

				//获取cookie
				String userInfo = "{\"loginName\":\"" + autoSign.getPhone() +"\",\"pwd\":\""+autoSign.getPwd()+"\"}";
				String JSESSIONID = signAdm.AdmLogin(userInfo);

				if(JSESSIONID != null) {

					//获取用户资料数据
					String ACCOUNT_DATA_RESULT = signAdm.JsoupToDataByCookieAndBody(SystemConstant.ACCOUNT_DATA, "{}", JSESSIONID);
					JSONObject account_data = JSONObject.parseObject(ACCOUNT_DATA_RESULT);

					UserInfoDto user = new UserInfoDto();

					String status_code = account_data.getString("code");
					if(status_code.equals("200")) {
						JSONArray dataList = account_data.getJSONArray("data");
						for (Object obj : dataList) {

							JSONObject __obj   = (JSONObject) obj;
							Integer  coinId    = __obj.getInteger("coinId");
							BigDecimal totalAmount = __obj.getBigDecimal("totalAmount");

							user.setAutosignid(autoSign.getId());
							if(coinId == 1001) { //USDT
								user.setUSTD( totalAmount );
							}else if(coinId == 1002) { // 可售余额
								user.setKSYE( totalAmount );
							}else if(coinId == 1003) { // 可售额度
								user.setKSED( totalAmount );
							}else if(coinId == 1004) { // 矿池钱包
								user.setKCQB(totalAmount );
							}else if(coinId == 1005) { // 矿池资产
								user.setKCZC( totalAmount );
							}else if(coinId == 1006) { // 信用积分
								user.setXYJF( totalAmount );
							}else if(coinId == 1007) { // ADM
								user.setADM( totalAmount );
							}else if(coinId == 1008) { // UT
								user.setUT( totalAmount );
							}else if(coinId == 1009) { // USDT冷钱包
								user.setUSTD2( totalAmount );
							}

						}

						//判断是否存在
						long isTrue = userInfoService.getCapitalListById(user.getAutosignid());
						if(isTrue > 0) {//存在就更新
							long COUNT = userInfoService.updateCapitalList(user);
							if(COUNT > 0) {
								//									System.out.println( "修改账户数据成功!" );
							}else {
								logger.error("修改账户数据失败!  phone = " + autoSign.getPhone());
							}
						}else {// 不存在就写入
							long COUNT = userInfoService.setCapitalList( user );
							if(COUNT > 0) {
								//									System.out.println( "写入账户数据成功!" );
							}else {
								logger.error( "写入账户数据失败!  phone = " + autoSign.getPhone());
							}
						}
					}

				}else {
					//资料错误, 请更新资料
					autoSign.setIsture(1);
					autoSign.setIsscan(1);
					autoSignService.updateAccountInfo(autoSign);
					logger.error("资料错误, 请更新资料 !!!  phone = " + autoSign.getPhone());
				}

			}

		}
		return Result.initSuccessResult("更新用户数据成功 , 共 "+list.size() + " 条");
	}
	
	/**
	 * 自动喂食
	 * @return
	 */
	@PostMapping("/feedAnimal")
	public Result<String> feedAnimal(){

		List<UserInfoDto> list = autoSignService.getUserNC();
		if(list.size() > 0) {

			for (UserInfoDto user : list) {

				//获取cookie
				String JSESSIONID = ADMLOGIN(user.getPhone() , user.getPwd());

				if(!JSESSIONID.equals("10021")) {
					//喂养前先收取鸡蛋
					String receiveEgg = signAdm.JsoupToDataByCookieAndBody(SystemConstant.receiveEgg, "{\"userAnimalId\":\""+user.getUserAnimalId()+"\"}" , JSESSIONID);
					JSONObject receiveEggJson = JSONObject.parseObject(receiveEgg);
					int _code_1_ = receiveEggJson.getInteger("code");
					String receiveMSG = receiveEggJson.getString("msg");
					if(_code_1_ == 200) {
						//喂养动物
						String feedAnimal = signAdm.JsoupToDataByCookieAndBody(SystemConstant.feedAnimal, "{\"userAnimalId\":\""+user.getUserAnimalId()+"\"}" , JSESSIONID);
						JSONObject feedAnimalJson = JSONObject.parseObject(feedAnimal);
						int _code_2_ = feedAnimalJson.getInteger("code");
						String msg = feedAnimalJson.getString("msg");
						if(_code_2_ == 200) {
							logger.info(user.getPhone() + " - 喂食"+msg+"!!! 时间: " + DateUtil.FMT_FN.format(new Date()));
						}else {
							logger.error(user.getPhone() + " - " + msg);
						}
					}else{

						logger.error(user.getPhone() +" : "+ receiveMSG);
						//喂养动物
						String feedAnimal = signAdm.JsoupToDataByCookieAndBody(SystemConstant.feedAnimal, "{\"userAnimalId\":\""+user.getUserAnimalId()+"\"}" , JSESSIONID);
						JSONObject feedAnimalJson = JSONObject.parseObject(feedAnimal);
						int _code_2_ = feedAnimalJson.getInteger("code");
						String msg = feedAnimalJson.getString("msg");
						if(_code_2_ == 200) {
							logger.info(user.getPhone() + " - 喂食"+msg+"!!! 时间: " + DateUtil.FMT_FN.format(new Date()));
						}else {
							logger.error(user.getPhone() + " - " + msg);
						}
					}
					
					updateUserInfo(JSESSIONID, user);
				}else {
					logger.error("id: "+user.getId()+" , loginName : " + user.getPhone() +" , 登录失败!!! " + DateUtil.FMT_FN.format(new Date()));

					AutoSign autoSign = new AutoSign();
					//资料错误, 请更新资料
					autoSign.setPhone(user.getPhone());
					autoSign.setIsture(2);
					autoSign.setIsscan(1);
					autoSignService.updateAccountInfo(autoSign);
				}

			}
			return Result.initSuccessResult("更新用户数据成功 , 共 "+list.size() + " 条");
		}else {
			return Result.initFailureResult(7001, "没有需要喂养的账号!");
		}
		
	}

	/**
	 * 自动检测账户信息
	 * @return
	 */
	@PostMapping("/autoCheckAccountInfo")
	public Result<String> autoCheckAccountInfo(){
		List<UserInfoDto> list = userInfoService.autoCheckAccountInfo();
		if(list.size() > 0){
			for (UserInfoDto user : list) {

				//获取cookie
				String JSESSIONID = ADMLOGIN(user.getPhone() , user.getPwd());
				if(JSESSIONID.equals("10021")) {
					logger.error("id: "+user.getId()+" , loginName : " + user.getPhone() +" , 登录失败!!! ");
				}else {
					updateUserInfo(JSESSIONID, user);
				}
			}
		}else{
			logger.info("No Need Update Account");
		}

		return Result.initSuccessResult("===============自动检测账户信息完成===============");
	}

	
	/**
	 * 更新资料
	 * @param JSESSIONID
	 * @param uid
	 */
	public void updateUserInfo(String JSESSIONID, UserInfoDto uid) {
        UserInfoDto user = new UserInfoDto();
		//-------------------- 用户资料数据 start ------------------------
		//获取用户资料数据
		String ACCOUNT_DATA_RESULT = signAdm.JsoupToDataByCookieAndBody(SystemConstant.ACCOUNT_DATA, "{}", JSESSIONID);
		JSONObject account_data = JSONObject.parseObject(ACCOUNT_DATA_RESULT);

		int status_code = account_data.getInteger("code");
		if(status_code == 200) {
			JSONArray dataList = account_data.getJSONArray("data");
			for (Object obj : dataList) {
				JSONObject __obj   = (JSONObject) obj;
				Integer  coinId    = __obj.getInteger("coinId");
				BigDecimal totalAmount = __obj.getBigDecimal("totalAmount");

				user.setAutosignid(uid.getId());
				if(coinId == 1001) { //USDT
					user.setUSTD( totalAmount );
				}else if(coinId == 1002) { // 可售余额
					user.setKSYE( totalAmount );
				}else if(coinId == 1003) { // 可售额度
					user.setKSED( totalAmount );
				}else if(coinId == 1004) { // 矿池钱包
					user.setKCQB(totalAmount );
				}else if(coinId == 1005) { // 矿池资产
					user.setKCZC( totalAmount );
				}else if(coinId == 1006) { // 信用积分
					user.setXYJF( totalAmount );
				}else if(coinId == 1007) { // ADM
					user.setADM( totalAmount );
				}else if(coinId == 1008) { // UT
					user.setUT( totalAmount );
				}else if(coinId == 1009) { // USDT冷钱包
					user.setUSTD2( totalAmount );
				}
			}
		}
		//-------------------- 用户资料数据 end ------------------------

		//-------------------- 农场部分 start ------------------------
		//查询农场动物
		String USER_ANIMAL_RESULT = signAdm.JsoupToDataByCookieAndBody(SystemConstant.userAnimalList, "{}" ,JSESSIONID);
		JSONObject userAnimalJson = JSONObject.parseObject(USER_ANIMAL_RESULT);

		int code = userAnimalJson.getInteger("code");

		//有动物的
		if(code == 200) {
			String data = userAnimalJson.getString("data");
			JSONObject dataJson = JSONObject.parseObject(data);
			JSONArray jsonArray = dataJson.getJSONArray("list");

			//由于目前只有1个种类
			JSONObject result = JSONObject.parseObject(jsonArray.get(0).toString());
			//系统鸡的编号 1001 
			int animalId = result.getInteger("animalId");
			//用户的动物编号
			int userAnimalId = result.getInteger("userAnimalId");
			
			long feedTime = result.getLong("feedTime");
			long nextFeedTime = feedTime + 1000 * 60 * 60 * 12;

			user.setIsOpenNC(1);
			user.setUserAnimalId(userAnimalId);
			user.setFeedTime(new Date(feedTime));
			user.setNextFeedTime(new Date(nextFeedTime));
		}
//		else if(code == 10008) {
//			logger.error(autoSign.getPhone() +" : "+userAnimalJson.toString() + ", 剩余 : " + count);
//		}
		//-------------------- 农场部分 end ------------------------


		//-------------------- 用户购买信息 start ------------------------
		//获取用户资料数据
		String levelInfoResult = signAdm.JsoupToDataByCookieAndBody(SystemConstant.getNextLevelInfo, "{}", JSESSIONID);
		JSONObject levelInfo = JSONObject.parseObject(levelInfoResult);

		String levelInfo_code = levelInfo.getString("code");
		if(levelInfo_code.equals("200")) {
			user.setAutosignid(uid.getId());
			String detail_data = levelInfo.getString("data");
			JSONObject json_detail = JSONObject.parseObject(detail_data);
			int hangUpCount = json_detail.getInteger("hangUpCount");
			int nextHangUpCount  = json_detail.getInteger("nextHangUpCount");

			user.setHangUpCount(hangUpCount);
			user.setNextHangUpCount(nextHangUpCount);
		}
		//-------------------- 用户购买信息 end ------------------------

		//判断是否存在
		long isTrue = userInfoService.getCapitalListById(user.getAutosignid());
		if(isTrue > 0) {//存在就更新
			long COUNT = userInfoService.updateCapitalList(user);
			if(COUNT > 0) {
				logger.info("修改账户数据成功!  phone = " + uid.getPhone());
			}else {
				logger.error("修改账户数据失败!  phone = " + uid.getPhone());
			}
		}else {// 不存在就写入
			long COUNT = userInfoService.setCapitalList( user );
			if(COUNT > 0) {
				logger.info("写入账户数据成功!  phone = " + uid.getPhone());
			}else {
				logger.error( "写入账户数据失败!  phone = " + uid.getPhone());
			}
		}
		
		logger.info("------------------------ phone: " + uid.getPhone() + " , 操作完成----------------------------");
    }
}
